var map = null;
var earthStation = undefined;
var EARTH_RADIUS = 6378137;
// 缓存的地图覆盖物，下次更新时清除
var overlays = [];
// 5G基站地图覆盖物缓存
var dotMap = {};

var freqColors = {
  "3400-3600": "#ff8ec9",
  "3600-3700": "#ffc04a",
  "3700-4200": "#00a4e9",
  "4800-4900": "#ce4dff",
  "4900-5000": "#c3eb36",
};
// 已协调颜色
var coordColor = "#20af4b";
// 未协调颜色
var uncoordColor = "#333";
// 有干扰颜色
var interfereColor = "#ed1b23";
// 无干扰颜色
var uninterfereColor = "#01a2e8";

// mock有干扰基站数据
var interfereList = "--------------------".split("").map(function (s, num) {
  var id = 40 + num;
  return {
    id: id,
    name: "5G基站" + id,
    lat: 116.32 + getMoveLng(39.93, random(2200, 500)),
    lng: 39.93 + getMoveLat(random(2200, 500)),
    isInterfere: true,
  };
});

// mock无干扰基站数据
var uninterfereList = "----------------".split("").map(function (s, num) {
  var id = 20 + num;
  return {
    id: id,
    name: "5G基站" + id,
    lat: 116.32 + getMoveLng(39.93, random(2200, 500)),
    lng: 39.93 + getMoveLat(random(2200, 500)),
    isInterfere: false,
  };
});

// mock 基站数据
var stations = [
  {
    id: "station-1",
    name: "北京瑞丰基金管理有限公司",
    satellite: "4500-4800",
    fiveG: "4900-5000",
    contact: "黄翔",
    tel: 1068619309,
    freqStart: 4950,
    freqEnd: 4976,
    lat: 116.32,
    lng: 39.93,
    code: "亚太2R",
    // 阻塞干扰
    blocks: [],
    // 有干扰
    interfere: interfereList,
    // 无干扰
    uninterfere: uninterfereList,
    // 0: 未协调 1: 已协调
    status: 1,
  },
];

/**
 * 初始化百度地图
 */
function init() {
  map = new BMap.Map("map", {
    enableMapClick: false,
  });
  var point = new BMap.Point(116.404, 39.915);
  map.centerAndZoom(point, 13);
  // 开启鼠标滚轮缩放
  // map.enableScrollWheelZoom(true);
}

/**
 * 下拉组件匹配函数
 */
function selectStation(stationId) {
  var matched = stations.find(function (station) {
    return station.id === stationId;
  });
  return matched;
}

/**
 * 初始化顶部表单事件：
 */
function initForm() {
  var $form = $("#search-form");
  var $station = $("#station");
  var $dropdown = $("#dropdown");
  var $condition = $("#condition");

  // 阻塞干扰
  var $blocked = $("#blocked");
  // 有干扰
  var $interfered = $("#interfered");
  // 无干扰
  var $uninterfered = $("#uninterfered");

  // 组装下拉组件
  stations.forEach(function (station) {
    var option = document.createElement("li");
    option.dataset.value = station.id;
    option.textContent = station.name;
    $dropdown.append([option]);
  });

  $(document).on("click", function () {
    $station.removeClass("active");
  });

  $station.on("click", function (evt) {
    evt.stopPropagation();
    $station.toggleClass("active");
  });

  // 下拉组件事件触发
  $dropdown.on("click", "li", function (evt) {
    evt.stopPropagation();
    $station.removeClass("placeholder active");

    earthStation = selectStation(this.dataset.value);

    $station.text(this.textContent);
    $condition.val(
      "卫星地球站：" +
        earthStation.satellite +
        "：5G基站：" +
        earthStation.fiveG
    );
  });

  // 表单提交：协调分析按钮
  $form.on("submit", function (evt) {
    evt.preventDefault();
    if (earthStation) {
      // 地球站坐标
      var center = new BMap.Point(earthStation.lat, earthStation.lng);
      // 箭头旋转角度
      var rotate = random(360, 0);
      createRadar(earthStation, center, rotate);

      // 点击协调分析后，显示侧边数据
      $("#aside").addClass("visible");

      var stationDetail = [
        '<div class="card opened">' + earthStation.name + "</div>",
        '<div class="card-detail">',
        '<p>联系人：<span class="card-value">' +
          earthStation.contact +
          "</span></p>",
        '<p>联系人电话：<span class="card-value">' +
          earthStation.tel +
          "</span></p>",
        '<p>接收频率范围(MHz)起：<span class="card-value">' +
          earthStation.freqStart +
          "</span></p>",
        '<p>接收频率范围(MHz)止：<span class="card-value">' +
          earthStation.freqEnd +
          "</span></p>",
        '<p>东经：<span class="card-value">' + earthStation.lat + "</span></p>",
        '<p>北纬：<span class="card-value">' + earthStation.lng + "</span></p>",
        '<p>卫星编号经：<span class="card-value">' +
          earthStation.code +
          "</span></p>",
        "</div>",
      ];

      // 侧边地球卫星站数据渲染
      $("#earth-station")
        .next(".collapse-content")
        .html(stationDetail.join(""));

      $(".zip").addClass("visible");

      // 单个5G基站的数据，假数据
      function render5GStation(g) {
        return [
          '<div class="card" data-id="' + g.id + '">' + g.name + "</div>",
          '<div class="card-detail">',
          '<p>东经：<span class="card-value">' +
            g.lat.toFixed(2) +
            "</span></p>",
          '<p>北纬：<span class="card-value">' +
            g.lng.toFixed(2) +
            "</span></p>",
          '<p>天线增益：<span class="card-value">25</span></p>',
          '<p>高度：<span class="card-value">25</span></p>',
          '<p>体制：<span class="card-value"></span></p>',
          '<p>频率：<span class="card-value">4960</span></p>',
          '<p>超过干扰允许标准：<span class="card-value">16.81dB</span></p>',
          '<p>距离：<span class="card-value">0.2635Km</span></p>',
          '<p>路径损耗：<span class="card-value">36.1864</span></p>',
          '<p>角度：<span class="card-value">108.937</span></p>',
          '<p>卫星地球站天线增益：<span class="card-value">-10.0</span></p>',
          '<p>干扰信号的值：<span class="card-value">-18.1864</span></p>',
          '<p>滤波器值：<span class="card-value">55</span></p>',
          "</div>",
        ];
      }

      // 生成对应干扰分组下的所有5G基站信息
      function render5GStations(list) {
        return list
          .map(function (item) {
            return render5GStation(item).join("");
          })
          .join("");
      }

      $blocked.find(".count").text("(" + earthStation.blocks.length + ")");

      if (earthStation.blocks.length) {
        $blocked
          .next(".collapse-content")
          .html(render5GStations(earthStation.blocks));
      } else {
        $blocked.next(".collapse-content").empty();
      }

      $interfered
        .find(".count")
        .text("(" + earthStation.interfere.length + ")");
      if (earthStation.interfere.length) {
        $interfered
          .next(".collapse-content")
          .html(render5GStations(earthStation.interfere));
      } else {
        $interfered.next(".collapse-content").empty();
      }

      $uninterfered
        .find(".count")
        .text("(" + earthStation.uninterfere.length + ")");
      if (earthStation.uninterfere.length) {
        $uninterfered
          .next(".collapse-content")
          .html(render5GStations(earthStation.uninterfere));
      } else {
        $uninterfered.next(".collapse-content").empty();
      }
    }
  });
}

function listenAsideEvents() {
  // 右侧蓝色分组展开收起事件
  $(document).on("click", ".collapse", function () {
    $(this).toggleClass("collapsed");
  });

  $(document).on("click", ".collapse-content", function (evt) {
    evt.stopPropagation();
  });

  // 右侧5G基站和卫星站白色卡片展开收起事件
  $(document).on("click", ".card", function () {
    $(this).toggleClass("opened");
  });

  $(document).on("click", ".card[data-id]", function () {
    var matchedDot = dotMap[this.dataset.id];
    if ($(this).hasClass("opened") && matchedDot) {
      open5GDetail(matchedDot);
    } else {
      map.closeInfoWindow();
    }
  });

  // 右下角箭头触发侧边栏信息的展开收起
  $("#toggle-aside").on("click", function () {
    $("#aside").toggleClass("visible");
  });
}

/**
 * 创建地图上的信号点
 */
function createCircleOverlay() {
  // 定义自定义覆盖物的构造函数
  function CircleOverlay(center, length, color, options) {
    this._center = center;
    this._length = length;
    this._color = color;
    this._options = options || {};
  }
  // 继承API的BMap.Overlay
  CircleOverlay.prototype = new BMap.Overlay();

  // 实现初始化方法
  CircleOverlay.prototype.initialize = function (map) {
    // 保存map对象实例
    this._map = map;
    // 创建div元素，作为自定义覆盖物的容器
    var div = document.createElement("div");
    div.className = this._options.className;
    div.addEventListener("click", this._options.onClick);

    div.style.position = "absolute";
    div.style.cursor = "pointer";
    // 可以根据参数设置元素外观
    div.style.width = this._length + "px";
    div.style.height = this._length + "px";
    div.style.backgroundColor = this._color;
    div.style.backgroundImage =
      "linear-gradient(to right bottom, rgba(255, 255, 255, .5), rgba(255, 255, 255, 0))";
    div.style.borderRadius = "50%";
    div.style.boxShadow = `0 0 10px ${this._color}`;
    // 将div添加到覆盖物容器中
    map.getPanes().markerPane.appendChild(div);
    // 保存div实例
    this._div = div;
    // 需要将div元素作为方法的返回值，当调用该覆盖物的show、
    // hide方法，或者对覆盖物进行移除时，API都将操作此元素。
    return div;
  };

  // 实现绘制方法
  CircleOverlay.prototype.draw = function () {
    // 根据地理坐标转换为像素坐标，并设置给容器
    var position = this._map.pointToOverlayPixel(this._center);
    this._div.style.left = position.x - this._length / 2 + "px";
    this._div.style.top = position.y - this._length / 2 + "px";
  };

  // 实现显示方法
  CircleOverlay.prototype.show = function () {
    if (this._div) {
      this._div.style.display = "";
    }
  };
  // 实现隐藏方法
  CircleOverlay.prototype.hide = function () {
    if (this._div) {
      this._div.style.display = "none";
    }
  };

  // 添加自定义方法
  CircleOverlay.prototype.toggle = function () {
    if (this._div) {
      if (this._div.style.display == "") {
        this.hide();
      } else {
        this.show();
      }
    }
  };

  return CircleOverlay;
}

/**
 * 移动纬度，单位米
 */
function getMoveLat(latMovement) {
  return (180 / (Math.PI * EARTH_RADIUS)) * latMovement;
}

/**
 * 转弧度
 */
function toRadians(deg) {
  return (Math.PI / 180) * deg;
}

/**
 * 移动经度，单位米
 */
function getMoveLng(lat, lngMovement) {
  return (
    (180 / (Math.PI * EARTH_RADIUS * Math.cos(toRadians(lat)))) * lngMovement
  );
}

/**
 * 随机数据，主要为了模拟信号数据
 */
function random(max = 1, min = 0) {
  var flag = Math.pow(-1, Math.ceil(Math.random() * 10));
  return Math.random() * max * flag + flag * min;
}

function open5GDetail(dot) {
  var color = dot.isInterfere ? interfereColor : uninterfereColor;
  var point = new BMap.Point(dot.lat, dot.lng);
  var content = [
    '<div class="g-dot-detail">',
    '<p>名称：<span class="g-dot-value">' + dot.name + "</span></p>",
    '<p>东经：<span class="g-dot-value">' + dot.lat.toFixed(2) + "</span></p>",
    '<p>北纬：<span class="g-dot-value">' + dot.lng.toFixed(2) + "</span></p>",
    '<p>天线增益：<span class="g-dot-value">25</span></p>',
    '<p>高度：<span class="g-dot-value">25</span></p>',
    '<p>频率：<span class="g-dot-value">4960</span></p>',
    "</div>",
  ].join("");
  var infoWindow = new BMap.InfoWindow(content, {
    width: 220, // 信息窗口宽度
    height: 100, // 信息窗口高度
    title:
      '<div class="g-dot-title"><span class="g-dot-color" style="background-color: ' +
      color +
      '"></span>' +
      dot.name +
      "</div>", // 信息窗口标题
  });
  map.openInfoWindow(infoWindow, point);
}

/**
 * 创建中间雷达数据
 */
function createRadar(station, center, degree) {
  overlays.forEach(function (overlay) {
    map.removeOverlay(overlay);
  });
  overlays = [];
  dotMap = {};

  map.centerAndZoom(center, 13);

  const outlineColor = freqColors[station.fiveG];
  // 4km的黑色圆
  var scope = new BMap.Circle(center, 4000, {
    strokeColor: outlineColor,
    strokeWeight: 3,
    strokeOpacity: 1,
    fillColor: "black",
    fillOpacity: 0.5,
    enableClicking: false,
  });
  map.addOverlay(scope);

  overlays.push(scope);

  var CircleOverlay = createCircleOverlay();

  /**
   *
   * @param dot 5G基站信息
   * @param interfered 是否是干扰
   */
  function render5GDot(dot) {
    var color = dot.isInterfere ? interfereColor : uninterfereColor;
    var point = new BMap.Point(dot.lat, dot.lng);
    var shape = new CircleOverlay(point, 6, color, {
      className: "dot-5g",
      onClick: function () {
        open5GDetail(dot);
      },
    });

    map.addOverlay(shape);
    overlays.push(shape);
    dotMap[dot.id] = dot;
  }

  station.interfere.forEach(render5GDot);
  station.uninterfere.forEach(render5GDot);

  // var statusColor = station.status === 1 ? coordColor : uncoordColor;
  // // 中间绿色圆+雷达标
  // var radarPoint = new CircleOverlay(center, 50, statusColor);
  // map.addOverlay(radarPoint);
  // overlays.push(radarPoint);

  // 中间雷达图标
  var icon = station.status === 1 ? "status-1.png" : "status-0.png";
  var radarIcon = new BMap.Icon(icon, new BMap.Size(55, 55), {
    // anchor: new BMap.Size(15, 22),
    imageSize: new BMap.Size(55, 55),
  });
  // 创建标注对象并添加到地图
  var marker = new BMap.Marker(center, { icon: radarIcon });
  marker.setZIndex(1);
  map.addOverlay(marker);
  overlays.push(marker);

  // 黄色箭头图标
  var arrowIcon = new BMap.Icon("arrow.png", new BMap.Size(162, 20), {
    // anchor: new BMap.Size(115, 14.5),
    imageSize: new BMap.Size(162, 20),
  });
  // 创建标注对象并添加到地图
  var arrow = new BMap.Marker(center, {
    icon: arrowIcon,
    rotation: degree,
  });
  map.addOverlay(arrow);
  overlays.push(arrow);
}

init();
initForm();
listenAsideEvents();
